import threading
import time

import nacos

from utils.logger_config import get_logger_config as logging

from .nacos_config import NacosConfig


class NacosService:
    def __init__(self, config=None):
        """
        初始化Nacos服务

        Args:
            config: NacosConfig实例，如果为None则创建默认配置
        """
        self.config = config if config else NacosConfig()
        self.client = None
        self.heartbeat_thread = None
        self.running = False
        self.logger = logging(name="nacos_service").get_logger()

    def init_client(self):
        """初始化Nacos客户端"""
        try:
            client_config = self.config.get_client_config()
            self.client = nacos.NacosClient(
                server_addresses=client_config["server_addresses"],
                namespace=client_config["namespace"],
            )
            return True
        except Exception as e:
            self.logger.error(f"初始化Nacos客户端失败: {str(e)}")
            return False

    def register_service(self, port=5555, metadata=None):
        """
        注册服务到Nacos

        Args:
            port: 服务端口
            metadata: 服务元数据

        Returns:
            是否注册成功
        """
        if not self.client:
            if not self.init_client():
                return False

        try:
            instance = self.config.get_service_instance(port=port, metadata=metadata)
            # 使用正确的方法名: add_naming_instance 而不是 add_instance
            success = self.client.add_naming_instance(
                service_name=instance["service_name"],
                ip=instance["ip"],
                port=instance["port"],
                weight=instance["weight"],
                enable=instance["enabled"],
                healthy=instance["healthy"],
                metadata=instance["metadata"],
                cluster_name="DEFAULT",
                group_name=instance["group_name"],
            )
            if success:
                self.logger.info(
                    f"服务注册成功: {instance['service_name']}@{instance['ip']}:{instance['port']}"
                )
                return True
            else:
                self.logger.error(
                    f"服务注册失败: {instance['service_name']}@{instance['ip']}:{instance['port']}"
                )
                return False
        except Exception as e:
            self.logger.error(f"服务注册异常: {str(e)}")
            return False

    def deregister_service(self, port=5555):
        """
        从Nacos注销服务

        Args:
            port: 服务端口

        Returns:
            是否注销成功
        """
        if not self.client:
            return False

        try:
            instance = self.config.get_service_instance(port=port)
            # 使用正确的方法名: remove_naming_instance 而不是 remove_instance
            success = self.client.remove_naming_instance(
                service_name=instance["service_name"],
                ip=instance["ip"],
                port=instance["port"],
                cluster_name="DEFAULT",
                group_name=instance["group_name"],
            )
            if success:
                self.logger.info(
                    f"服务注销成功: {instance['service_name']}@{instance['ip']}:{instance['port']}"
                )
                return True
            else:
                self.logger.error(
                    f"服务注销失败: {instance['service_name']}@{instance['ip']}:{instance['port']}"
                )
                return False
        except Exception as e:
            self.logger.error(f"服务注销异常: {str(e)}")
            return False

    def start_heartbeat(self, port=5555, interval=5):
        """
        启动心跳线程

        Args:
            port: 服务端口
            interval: 心跳间隔（秒）
        """
        if self.heartbeat_thread and self.heartbeat_thread.is_alive():
            return

        self.running = True
        self.heartbeat_thread = threading.Thread(
            target=self._heartbeat_task, args=(port, interval), daemon=True
        )
        self.heartbeat_thread.start()
        self.logger.info(f"心跳线程已启动，间隔: {interval}秒")

    def stop_heartbeat(self):
        """停止心跳线程"""
        self.running = False
        if self.heartbeat_thread:
            self.heartbeat_thread.join(timeout=2)
            self.heartbeat_thread = None
            self.logger.info("心跳线程已停止")

    def _heartbeat_task(self, port, interval):
        """
        心跳任务

        Args:
            port: 服务端口
            interval: 心跳间隔（秒）
        """
        instance = self.config.get_service_instance(port=port)
        while self.running:
            try:
                # 使用正确的参数调用send_heartbeat方法
                self.client.send_heartbeat(
                    service_name=instance["service_name"],
                    ip=instance["ip"],
                    port=instance["port"],
                    cluster_name="DEFAULT",
                    weight=instance["weight"],
                    metadata=instance["metadata"],
                    ephemeral=True,  # 临时实例，会自动注销
                    group_name=instance["group_name"],
                )
                self.logger.debug(
                    f"发送心跳成功: {instance['service_name']}@{instance['ip']}:{instance['port']}"
                )
            except Exception as e:
                self.logger.error(f"发送心跳失败: {str(e)}")
                # 尝试重新注册
                try:
                    self.register_service(port=port)
                except:
                    pass

            time.sleep(interval)
